package com.wjd.gulimall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjd.common.utils.PageUtils;
import com.wjd.common.utils.Query;
import com.wjd.gulimall.product.dao.AttrDao;
import com.wjd.gulimall.product.dto.AttrDto;
import com.wjd.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.wjd.gulimall.product.entity.AttrEntity;
import com.wjd.gulimall.product.entity.AttrGroupEntity;
import com.wjd.gulimall.product.entity.CategoryEntity;
import com.wjd.gulimall.product.service.AttrAttrgroupRelationService;
import com.wjd.gulimall.product.service.AttrGroupService;
import com.wjd.gulimall.product.service.AttrService;
import com.wjd.gulimall.product.service.CategoryService;
import com.wjd.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String attrTypeStr = (String) params.get("attrType");
        Integer attrType = "base".equalsIgnoreCase(attrTypeStr) ? 1 : 0;
        Long catelogId = (Long) params.getOrDefault("catelogId", 0L);
        String key = (String) params.get("key");
        String sidx = (String) params.get("sidx");
        String order = (String) params.get("order");
        LambdaQueryWrapper<AttrEntity> query = new LambdaQueryWrapper<AttrEntity>()
                .eq(AttrEntity::getAttrType, attrType)
                .eq(!Objects.equals(0L, catelogId), AttrEntity::getCatelogId, catelogId)
                .and(StringUtils.isNotBlank(key), wrapper -> wrapper
                        .eq(AttrEntity::getAttrId, key)
                        .or()
                        .like(AttrEntity::getAttrName, key))
                .last(StringUtils.isNotBlank(sidx), "ORDER BY " + params.get("sidx") + " " + order);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), query
        );
        PageUtils result = new PageUtils(page);

        List<AttrVo> voList = page.getRecords().stream().map(this::getAttrDetail).collect(Collectors.toList());
        result.setList(voList);

        return result;
    }

    @Override
    public AttrVo getAttr(Long attrId) {
        AttrEntity entity = getById(attrId);
        if (entity == null) {
            return null;
        }

        return getAttrDetail(entity);
    }

    @Transactional
    @Override
    public void saveAttr(AttrDto attrDto) {
        // 保存属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrDto, attrEntity);
        save(attrEntity);

        // 保存属性与分组的关联关系
        if (attrDto.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(attrEntity.getAttrId());
            relation.setAttrGroupId(attrDto.getAttrGroupId());
            attrAttrgroupRelationService.save(relation);
        }
    }

    @Transactional
    @Override
    public void updateAttr(AttrDto attrDto) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrDto, attrEntity);
        updateById(attrEntity);

        // 更新属性与分组的关联关系
        if (attrDto.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relation = getAttrGroupRelation(attrEntity);
            if (relation != null) {
                relation.setAttrGroupId(attrDto.getAttrGroupId());
                attrAttrgroupRelationService.updateById(relation);
            } else {
                // 如果没有关联关系，则创建新的
                relation = new AttrAttrgroupRelationEntity();
                relation.setAttrId(attrEntity.getAttrId());
                relation.setAttrGroupId(attrDto.getAttrGroupId());
                attrAttrgroupRelationService.save(relation);
            }
        }
    }

    @Override
    public void deleteAttrs(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除属性与分组的关联关系
        attrAttrgroupRelationService.remove(
                new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                        .in(AttrAttrgroupRelationEntity::getAttrId, ids)
        );
        // 删除属性
        removeByIds(ids);
    }

    /**
     * 获取属性详细信息，包括分组和分类名称
     *
     * @param attr 属性实体
     * @return AttrVo
     */
    private AttrVo getAttrDetail(AttrEntity attr) {
        AttrVo attrVo = new AttrVo();
        BeanUtils.copyProperties(attr, attrVo);
        // 属性分组
        AttrGroupEntity attrGroup = getAttrGroup(attr);
        if (attrGroup != null) {
            attrVo.setAttrGroupId(attrGroup.getAttrGroupId());
            attrVo.setGroupName(attrGroup.getAttrGroupName());
        }
        // 分类名称
        CategoryEntity category = getCategory(attr);
        if (category != null) {
            attrVo.setCatelogName(category.getName());
        }
        // 设置分类路径
        List<Long> path = categoryService.getCategoryPath(attr.getCatelogId());
        attrVo.setCatelogPath(path);
        return attrVo;
    }

    /**
     * 获取属性对应的分类信息
     *
     * @param attr 属性实体
     * @return CategoryEntity
     */
    private CategoryEntity getCategory(AttrEntity attr) {
        if (attr == null || attr.getCatelogId() == null) {
            return null;
        }
        return categoryService.getById(attr.getCatelogId());
    }

    /**
     * 获取属性对应的分组信息
     *
     * @param attr 属性实体
     * @return AttrGroupEntity
     */
    private AttrGroupEntity getAttrGroup(AttrEntity attr) {
        if (attr == null || attr.getAttrId() == null) {
            return null;
        }
        AttrAttrgroupRelationEntity relation = getAttrGroupRelation(attr);
        if (relation != null) {
            return attrGroupService.getById(relation.getAttrGroupId());
        }
        return null;
    }

    /**
     * 获取属性与分组的关联关系
     *
     * @param attr 属性实体
     * @return AttrAttrgroupRelationEntity
     */
    private AttrAttrgroupRelationEntity getAttrGroupRelation(AttrEntity attr) {
        return attrAttrgroupRelationService.getOne(
                new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
        );
    }

}